package com.platform.web.controller.system;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson2.JSONException;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.system.domain.ProCart;
import com.platform.system.domain.ProProduct;
import com.platform.system.domain.ProProductOrder;
import com.platform.system.domain.bo.PreOrderBo;
import com.platform.system.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.platform.common.annotation.Log;
import com.platform.common.core.controller.BaseController;
import com.platform.common.core.domain.AjaxResult;
import com.platform.common.enums.BusinessType;
import com.platform.system.domain.ProOrder;
import com.platform.common.utils.poi.ExcelUtil;
import com.platform.common.core.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author platform
 * @date 2025-02-23
 */
@Tag(name = "订单", description = "")
@RestController
@RequestMapping("/system/order")
public class ProOrderController extends BaseController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IProOrderService proOrderService;
    @Autowired
    private IProCartService proCartService;
    @Autowired
    private IProProductService proProductService;
    @Autowired
    private IProProductOrderService proProductOrderService;


    /**
     * 获取订单的确认信息
     *
     * @return
     */
    @PostMapping("/pre")
    public AjaxResult pre(@RequestBody PreOrderBo preOrderBo) throws JSONException {
        String cartsStr = preOrderBo.getCarts();
        List<ProCart> carts = JSONUtil.toBean(cartsStr, new TypeReference<List<ProCart>>() {}, true);
        Map<String, Object> all = proCartService.findAll(carts);
        return success(all);
    }

    /**
     * 查询订单列表
     */
    @Operation(summary = "查询订单列表")
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProOrder proOrder) {
        startPage();
        List<ProOrder> list = proOrderService.selectProOrderList(proOrder);
        return getDataTable(list);
    }

    /**
     * 查询订单列表
     */
    @Operation(summary = "查询订单列表")
    @GetMapping("/listAll")
    public TableDataInfo listAll(ProOrder proOrder) {
        startPage();
        proOrder.setUserId(getUserId());
        List<ProOrder> list = proOrderService.selectProOrderListAll(proOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @Operation(summary = "导出订单列表")
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProOrder proOrder) {
        List<ProOrder> list = proOrderService.selectProOrderList(proOrder);
        ExcelUtil<ProOrder> util = new ExcelUtil<ProOrder>(ProOrder.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @Operation(summary = "获取订单详细信息")
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(proOrderService.selectProOrderById(id));
    }

    /**
     * 新增订单
     */
    @Operation(summary = "新增订单")
//    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProOrder proOrder) {
        proOrder.setUserId(getUserId());
        proOrder.setCreateBy(getUsername());
        proOrderService.insertProOrder(proOrder);

        List<ProCart> carts = JSONUtil.toBean(proOrder.getCarts(), new TypeReference<List<ProCart>>() {}, true);
        for (ProCart cart : carts) {
            Long count = cart.getCount();
            Long goodsId = cart.getProducproId();

            // 扣库存
            ProProduct goods = proProductService.selectProProductById(goodsId);
            if(goods.getStore() - cart.getCount() < 0) {
                AjaxResult.error("库存不足");
            }
            goods.setStore(goods.getStore() - cart.getCount());
            goods.setSales(goods.getSales() + cart.getCount());
            proProductService.updateProProduct(goods);

            ProProductOrder orderGoods = new ProProductOrder();
            orderGoods.setOrderId(proOrder.getId());
            orderGoods.setProducproId(goodsId);
            orderGoods.setCount(count);
            proProductOrderService.insertProProductOrder(orderGoods);

            // 清空购物车商品
            for (ProCart proCart : carts) {
                proCartService.deleteProCartById(proCart.getId());
            }
        }
        return success();
    }

    @Transactional
    @Operation(summary = "付款")
    @PutMapping("/pay/{id}")
    public AjaxResult pay(@PathVariable Long id) {
        ProOrder order = proOrderService.selectProOrderById(id);
        BigDecimal totalPrice = order.getTotalPrice();

        Long userId = getUserId();
        SysUser user = sysUserService.selectUserById(userId);

        if (user.getAccount().compareTo(totalPrice) <= 0) {
            return error("余额不足");
        }

        Long points = proProductOrderService.findProductPointByOrderId(order.getId());
        // 更新余额
        user.setAccount(user.getAccount().subtract(totalPrice));
        // 更新积分
        user.setPoints(user.getPoints() + points);
        sysUserService.updateUser(user);

        order.setState(1);
        proOrderService.updateProOrder(order);

        sysUserService.updateAccount(getUserId(), user.getAccount().subtract(totalPrice));

        return success();
    }

    /**
     * 修改订单
     */
    @Operation(summary = "修改订单")
//    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProOrder proOrder) {
        proOrder.setUpdateBy(getUsername());
        return toAjax(proOrderService.updateProOrder(proOrder));
    }

    /**
     * 删除订单
     */
    @Operation(summary = "删除订单")
//    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(proOrderService.deleteProOrderByIds(ids));
    }
}
